package com.dsideal.cloud.cas.client.config;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.dsideal.cloud.cas.client.entity.StudentRowMapper;
import com.dsideal.cloud.cas.client.entity.TeacherRowMapper;
import com.dsideal.cloud.cas.client.entity.UserLog;
import com.dsideal.cloud.common.log.DsLogger;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 临时数据库查询，用以操作数据库信息
 */
@Component("mysqlConfig")
public class MysqlConfig {

    private final static DsLogger log = DsLogger.buildLogger(MysqlConfig.class);

    @Autowired
    JdbcTemplate jdbcTemplate;

    public  List< Map<String, Object>> queryByname(String name){

        String sql = " select u.user_name,u.login_password,u.login_name,u.base_user_id, u.bureau_id ,ru.base_role_user_id,r.role_code,r.data_scope ,r.base_role_id " +
                "FROM base_user u  " +
                "left join base_role_user ru on u.base_user_id =ru.base_user_id and ru.delete_flag='0'" +
                " LEFT JOIN base_role r on ru.base_role_id=r.base_role_id  AND r.delete_flag = '0' " +
                " where u.delete_flag = '0' and login_name = ?  and  " +
                "CASE  WHEN r.base_role_id is null or r.base_role_id='' THEN 1=1 " +
                "ELSE " +
                " r.delete_flag='0' " +
                "END ";


       List< Map<String, Object>> list =new ArrayList<>();
        try {
            list=jdbcTemplate.queryForList(sql,name);
        } catch (Exception e) {
            log.error("queryByname error {}", e);
        }

        return list;
    }

    public  List< Map<String, Object>> queryById(String userId){

        String sql = " select u.user_name,u.login_password,u.login_name,u.base_user_id, u.bureau_id ,ru.base_role_user_id,r.role_code,r.data_scope ,r.base_role_id " +
                "FROM base_user u  " +
                "left join base_role_user ru on u.base_user_id =ru.base_user_id and ru.delete_flag='0'" +
                " LEFT JOIN base_role r on ru.base_role_id=r.base_role_id  AND r.delete_flag = '0' " +
                " where u.delete_flag = '0' and u.yj_id = ?  and  " +
                "CASE  WHEN r.base_role_id is null or r.base_role_id='' THEN 1=1 " +
                "ELSE " +
                " r.delete_flag='0' " +
                "END ";


       List< Map<String, Object>> list =new ArrayList<>();
        try {
            list=jdbcTemplate.queryForList(sql,userId);
        } catch (Exception e) {
            log.error("queryByname error {}", e);
        }

        return list;
    }

    public  List< Map<String, Object>> queryById2(String userId){

        String sql = " select u.user_name,u.login_password,u.login_name,u.base_user_id, u.bureau_id ,ru.base_role_user_id,r.role_code,r.data_scope ,r.base_role_id " +
                "FROM base_user u  " +
                "left join base_role_user ru on u.base_user_id =ru.base_user_id and ru.delete_flag='0'" +
                " LEFT JOIN base_role r on ru.base_role_id=r.base_role_id  AND r.delete_flag = '0' " +
                " where u.delete_flag = '0' and u.yj_id = ?  "
//                "and  " +
//                "CASE  WHEN r.base_role_id is null or r.base_role_id='' THEN 1=1 " +
//                "ELSE " +
//                " r.delete_flag='0' " +
//                "END "
                ;


       List< Map<String, Object>> list =new ArrayList<>();
        try {
            list=jdbcTemplate.queryForList(sql,userId);
        } catch (Exception e) {
            log.error("queryByname error {}", e);
        }

        return list;
    }

    public Map<String, Object> queryCommonLoginWay(){
        String sql = "select config_value from base_global_config where config_key = 'common.login.way' and delete_flag = '0'";
        Map<String, Object> map = Maps.newHashMap();
        try {
            map = jdbcTemplate.queryForMap(sql);
        } catch (Exception e) {
            log.error("queryCommonLoginWay error {}", e);
        }
        return map;
    }

    public void updateUserYjToken(String yjUserId, String yjToken){
        String sql = "update base_user set yj_token = ? where yj_id = ? and delete_flag = '0'";
        String[] params = new String[] {yjToken, yjUserId};
        try {
            jdbcTemplate.update(sql, params);
        } catch (Exception e) {
            log.error("updateUserYjToken error {}", e);
        }
    }

    public void updateUserYjToken(String yjUserId, String yjToken, String yjRoleIds){
        String sql = "update base_user set yj_token = ?, yj_role_ids = ? where yj_id = ?";
        String[] params = new String[] {yjToken, yjRoleIds, yjUserId};
        try {
            jdbcTemplate.update(sql, params);
        } catch (Exception e) {
            log.error("updateUserYjToken error {}", e);
        }
    }

    public List<Map<String, Object>> queryGlobalConfig() {
        String sql = "select * from base_global_config where delete_flag = '0'";
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
        return result;
    }

    @DS("business")
    public Map<String, Object> testDynamicDatasource(String teacherId) {
        String sql = "select * from business_teacher where business_teacher_id = ?";
        Map<String, Object> result = jdbcTemplate.queryForMap(sql, teacherId);
        return result;
    }

    /***
     * @Author zw
     * @Description 根据用户id查询身份信息
     * @Date 下午 7:10 2021/4/19
     * @Param [userId]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String, Object> queryIdentity(String userId) {
        String sql = "select identity_code from base_user where base_user_id = ?";
        Map<String, Object> result = jdbcTemplate.queryForMap(sql, userId);
        return result;
    }

    /***
     * @Author zw
     * @Description 查询学生登录用户信息
     * @Date 下午 3:23 2021/4/19
     * @Param [userId]
     * @return com.dsideal.cloud.cas.client.entity.UserLog
     **/
    public UserLog queryStudentInfo(String userId) {
        String sql = "select a.base_user_id,a.user_name,a.login_name,a.yj_id,a.bureau_id,o.organization_name,o.yj_xd," +
                " a.identity_code,a.sex,bc.class_name,bc.yj_nj,bc.base_class_id from base_user a " +
                " left join base_organization o on a.bureau_id = o.base_organization_id " +
                " left join base_student_class bsc on a.base_user_id = bsc.base_user_id " +
                " left join base_class bc on bsc.base_class_id = bc.base_class_id " +
                " where a.delete_flag = '0' and o.delete_flag = '0' and bsc.delete_flag = '0' and bc.delete_flag = '0' " +
                " and a.base_user_id = ? ";
        UserLog userLog = jdbcTemplate.queryForObject(sql,new StudentRowMapper(),userId);
        return userLog;
    }

    /***
     * @Author zw
     * @Description 查询教师登录用户信息
     * @Date 下午 3:23 2021/4/19
     * @Param [userId]
     * @return com.dsideal.cloud.cas.client.entity.UserLog
     **/
    public UserLog queryTeacherInfo(String userId) {
        String sql = "select a.base_user_id,a.user_name,a.login_name,a.yj_id,a.bureau_id,o.organization_name,o.yj_xd," +
                " a.identity_code,a.sex from base_user a " +
                " left join base_organization o on a.bureau_id = o.base_organization_id  " +
                " where a.delete_flag = '0' and o.delete_flag = '0' and  " +
                " a.base_user_id = ? ";
        UserLog userLog = jdbcTemplate.queryForObject(sql,new TeacherRowMapper(),userId);
        return userLog;
    }

    /***
     * @Author zw
     * @Description 获取登录用户当前学期的任课信息
     * @Date 上午 11:33 2021/4/19
     * @Param [userId]
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    @DS("business")
    public List< Map<String, Object>> queryTeachPlan(String userId) {
        String sql = "SELECT a.base_user_id,a.business_stage_code,a.business_subject_code,c.stage_name,d.subject_name " +
                " FROM business_teach_plan a " +
                " LEFT JOIN business_term b ON a.business_term_id = b.business_term_id " +
                " LEFT JOIN business_stage c ON a.business_stage_code = c.stage_code " +
                " LEFT JOIN business_subject d ON a.business_subject_code = d.subject_code " +
                " WHERE b.current_term_flag = '1' AND c.delete_flag = '0' AND d.delete_flag = '0' " +
                " AND a.base_user_id = ? ";
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql,userId);
        return result;
    }

    /***
     * @Author zw
     * @Description 插入用户登录日志
     * @Date 下午 7:56 2021/4/19
     * @Param [userLog]
     * @return void
     **/
    public int insertUserLog(UserLog userLog) {
        String sql = "INSERT INTO `base_user_log`(`base_user_log_id`, `base_user_id`, `user_name`, `bureau_stage`," +
                " `login_name`, `yj_id`, `bureau_id`, `bureau_name`, `identity_code`, `sex`, `grade_name`, `base_class_id`, `class_name`, " +
                " `login_type`, `account_type`, `login_ip`, `equipment_type`, `login_result`, `login_remark`, `stage_code`, `stage_name`, `subject_code`, `subject_name`, `create_time`) " +
                " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
        int result = jdbcTemplate.update(sql, userLog.getBaseUserLogId(),userLog.getBaseUserId(),userLog.getUserName(),userLog.getBureauStage()
                ,userLog.getLoginName(),userLog.getYjId(),userLog.getBureauId(),userLog.getBureauName(),userLog.getIdentityCode(),userLog.getSex()
                ,userLog.getGradeName(),userLog.getBaseClassId(),userLog.getClassName(),userLog.getLoginType(),userLog.getAccountType()
                ,userLog.getLoginIp(),userLog.getEquipmentType(),userLog.getLoginResult(),userLog.getLoginRemark(),userLog.getStageCode()
                ,userLog.getStageName(),userLog.getSubjectCode(),userLog.getSubjectName(),userLog.getCreateTime());

        return result;
    }


    public  List< Map<String, Object>> queryLogin(){
        String sql = "select yj_user AS yjUser,date_format(create_time, '%Y-%m-%d %H:%i:%s') AS createTime FROM login";
        List< Map<String, Object>> list =new ArrayList<>();
        try {
            list=jdbcTemplate.queryForList(sql);
        } catch (Exception e) {
            log.error("queryByname error {}", e);
        }
        return list;
    }

}
